package cn.song.controller.common;

import cn.hutool.core.util.StrUtil;
import cn.song.ExcelDemoApplication;
import cn.song.entity.easyexcel.ExcelModel;
import cn.song.mapper.UserModelMapper;
import cn.song.model.DownloadDto;
import cn.song.model.R;
import cn.song.util.FilePath;
import cn.song.util.easyexcel.EasyExcelUtils;
import cn.song.util.easyexcel.model.BatchCount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static cn.song.util.easyexcel.model.BatchCount.handleFailedInsert;
import static cn.song.util.easyexcel.model.BatchCount.handleSuccessfulInsert;
import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * 公共服务
 *
 * @author SongRenShuo
 * @date 2025/01/20
 */
@Slf4j
@Service
public class CommonService {

    @Autowired
    private EasyExcelUtils easyExcelUtils;
    @Autowired
    private UserModelMapper userModelMapper;

    /**
     * 导出 - 异步 - 导出任务列表
     *
     * @param dto dto
     * @param ignoreParamList 忽略参数列表
     * @param downloadDto 下载 DTO
     * @date 2025/07/27
     * @author SongRenShuo
     * @return {@link R }
     */
    public R downloads(ExcelModel dto, List<String> ignoreParamList, DownloadDto downloadDto) {
        String fileName = FilePath.getFileNameDate(downloadDto.getFileName() + "_") + ".xlsx";

        // 分页查询分批导出
        return easyExcelUtils.exportInBatches(fileName, FilePath.DOWN_ABSOLUTE, FilePath.DOWN_RELATIVE,
                ExcelModel.class,
                () -> userModelMapper.selectList(null),
                // 注释  userModelMapper.selectCount(null), 后为一次性导出
                userModelMapper.selectCount(null),
                downloadDto, ignoreParamList, dto);

    }

    /**
     * 文件上传 - 核心方法示例
     *
     * @param cachedDataList 缓存数据列表
     * @param downloadDto        导出DTO
     * @return {@link BatchCount }
     * @date 2024/03/20
     * @author SongRenShuo
     */
    public BatchCount insertImport(List<ExcelModel> cachedDataList, DownloadDto downloadDto) {

        // 成功计数器
        int sCount = 0;
        // 错误计数器
        int eCount = 0;
        // 存储结果的列表
        ArrayList<BatchCount.BatchCountDto> errorMsg = new ArrayList<>();
        // 存储总计数器和数据列表
        for (ExcelModel excelModel : cachedDataList) {
            if (excelModel.getId() == null) {
                handleFailedInsert(errorMsg, eCount++, "", excelModel, "序号不能为空");
                continue;
            }

            R insert = new R();
            try {
                insert = R.success("核心业务处理.....");

                if (!insert.isCode()) {
                    handleFailedInsert(errorMsg, eCount++, excelModel.getId(), excelModel, insert.getMsg());
                } else {
                    handleSuccessfulInsert(errorMsg, sCount++, excelModel.getId());
                }

            } catch (Exception e) {
                log.error("批量上传异常，订单号：{},具体原因：", excelModel.getId(), e);
                String message = StrUtil.length(e.getMessage()) > 200 ? "上传异常,请联系管理员" : e.getMessage();
                String msg = isBlank(insert.getMsg()) ? message : insert.getMsg();
                handleFailedInsert(errorMsg, eCount++, excelModel.getId(), excelModel, msg);
            }

        }

        BatchCount batchCount = new BatchCount(cachedDataList.size());
        batchCount.setSuccessCount(sCount);
        batchCount.setErrorCount(eCount);
        batchCount.setErrorMsg(errorMsg);

        return batchCount;
    }

    /**
     * 获取登录账户
     *
     * @param zhangHu 张胡
     * @param request 请求
     * @return {@link String }
     * @date 2025/01/20
     * @author SongRenShuo
     */
    public String getZhangHu(String zhangHu, HttpServletRequest request) {

        // 真实环境需要从request中获取用户信息

        return "test";
    }


    /**
     * 获取路径
     *
     * @return {@link String }
     * @date 2024/03/28
     * @author SongRenShuo
     */
    public static String getPath() {
        ApplicationHome ah = new ApplicationHome(ExcelDemoApplication.class);
        File file = ah.getSource();
        String path = file.getParentFile().toString();
        log.info("当前程序路径：{}", path);
        return path;
    }

}
